<template>
  <a-form :model="formState" name="basic" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }" autocomplete="off"
    @finish="onFinish" @finishFailed="onFinishFailed" class="pwdCheck" :rules="rules">
    <div class="title">设置密码</div>

    <!-- 图形验证码 -->
    <a-form-item label="验证码" name="pictureCode">
      <div class="captcha-container">
        <a-input v-model:value="formState.pictureCode" placeholder="请输入图形验证码" />
        <img 
          :src="captchaUrl" 
          class="pictureCode"
          @click="refreshCaptcha"
          alt="验证码"
        />
      </div>
    </a-form-item>

    <!-- 密码 -->
    <a-form-item label="密码" name="password">
      <a-input-password v-model:value="formState.password" />
    </a-form-item>

    <!-- 确认密码 -->
    <a-form-item label="确认密码" name="confirm">
      <a-input-password v-model:value="formState.confirm" />
    </a-form-item>

    <!-- 上传用户头像 -->
    <UploadUserAvatar :changeAvatar='changeAvatar' />

    <!-- 提交 -->
    <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
      <a-button type="primary" html-type="submit">提交</a-button>
    </a-form-item>

    <!-- 返回上一步 -->
    <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
      <a-button type="primary" @click="prev">上一步</a-button>
    </a-form-item>
  </a-form>
</template>

<script setup>
import UploadUserAvatar from './UploadUserAvatar.vue'
import { message } from 'ant-design-vue';
import { reactive, ref } from 'vue';
import { getCaptcha, getRegister } from '../../../api/accountServer'
const { toChangePop, userInfo } = defineProps(['toChangePop', 'userInfo'])

const formState = reactive({
  pictureCode: '',
  password: '',
  confirm: '',
  url: ''
});

// 验证码URL
const captchaUrl = ref('http://localhost:8888/account-server/api/notify/v1/captcha?deviceId=1')

// 刷新验证码
const refreshCaptcha = () => {
  captchaUrl.value = `http://localhost:8888/account-server/api/notify/v1/captcha?deviceId=1&t=${Date.now()}`
}

const changeAvatar = (url) => {
  formState.url = url
}

const onFinish = values => {
  console.log('sucess:', values);
  if (!formState.url) {
    message.error('请上传头像！')
    return
  }
  
  // 这里添加验证码校验逻辑
  if (!validateCaptcha()) {
    message.error('验证码错误，请重新输入！')
    return
  }
  
  getRegisterData()
};

const onFinishFailed = errorInfo => {
  console.log('Failed:', errorInfo);
};

/**
 * 验证码校验
 */
const validateCaptcha = () => {
  // 这里应该调用后端接口验证验证码是否正确
  // 暂时模拟验证，实际应该调用接口验证
  if (formState.pictureCode && formState.pictureCode.length === 4) {
    return true
  }
  return false
}

/**
 * 确认密码校验
 */
let validatePass = async (_rule, value) => {
  if (value === '') {
    return Promise.reject('请输入确认密码！');
  } else if (value !== formState.password) {
    return Promise.reject("两次密码不一致！");
  } else {
    return Promise.resolve();
  }
};

/**
 * 校验规则
 */
const rules = {
  pictureCode: [
    { required: true, trigger: 'blur', message: '请输入图形验证码!' },
    { pattern: /^[0-9a-zA-Z]{4}$/, message: '验证码格式不正确', trigger: 'blur' }
  ],
  password: [
    { required: true, trigger: 'blur', message: '请输入密码!' }, 
    { pattern: /^.{6,16}$/, message: '请输入6~16位密码', trigger: 'blur' }
  ],
  confirm: [{ required: true, validator: validatePass, trigger: 'blur' }]
};

/**
 * 上一步
 */
const prev = () => {
  toChangePop('register')
}

/**
 * 注册接口
 */
const getRegisterData = async () => {
  try {
    const res = await getRegister({
      phone: userInfo.phone,
      pwd: formState.password,
      username: userInfo.username,
      code: formState.pictureCode,  // 使用图形验证码作为验证码
      headImg: formState.url
    })
    if (res?.code === 0) {
      message.success('注册成功！')
      toChangePop('login')
    } else if (res?.code === 240003) {
      message.error('验证码错误！')
      refreshCaptcha()
     // 验证码错误时刷新验证码
    } else if (res?.code === -1) {
      message.error('该手机号已注册！')
    } else {
      message.error(res?.message || '注册失败，请重试！')
    }
  } catch (error) {
    message.error('网络错误，请重试！')
    console.error('注册错误:', error)
  }
}
</script>

<style lang='less' scoped>
.captcha-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(#basic_pictureCode) {
  width: 130px;
}

.codeButton {
  width: 120px !important;
}

.pictureCode {
  width: 120px;
  height: 32px;
  cursor: pointer;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
}

.title {
  font-size: 18px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 20px;
}

.pwdCheck {
  max-width: 400px;
  margin: 0 auto;
}
</style>